package com.starblink.library.widget.product

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.postDelayed
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.apollographql.apollo3.api.Optional
import com.blankj.utilcode.util.VibrateUtils
import com.bumptech.glide.load.DecodeFormat
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.data.model.product.IProductFWrap
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FontUtil
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.basic.apollo.ext.ApolloValSetExt.apolloValue
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.ext.load
import com.starblink.basic.log.SKLogger
import com.starblink.basic.style.R
import com.starblink.library.widget.databinding.*
import com.starblink.library.widget.novice_guide.control.GuidePopStatusControl
import com.starblink.library.widget.product.parity.PriceParityDialog
import com.starblink.library.widget.product.pop.GoodsFindSimilarPop
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.FetchProductListByStdIdQuery
import com.starblink.rocketreserver.MoveProductList2WishListMutation
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.fragment.SpuOffer
import com.starblink.rocketreserver.type.CollectItem
import com.starblink.rocketreserver.type.StdProductIdQuery
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlin.math.max

/**
 * Feeds 商品卡片
 */
@SuppressLint("MissingPermission")
class ProductCardView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleRes: Int = 0,
) : ConstraintLayout(context, attrs, defStyleRes) {

    companion object {
        const val TAG = "ProductCardView"
        const val RATIO_LIMIT = 9F / 16F
        const val SEARCH_WORD_SOURCE_HOT = 1 // 搜索词来源-Trending词
        const val SEARCH_WORD_SOURCE_SHADING = 2 //
    }

    private val collectImg = R.drawable.ic_prd_collect2
    private val collectedImg = R.drawable.ic_prd_collected2

    var productWrap: IProductFWrap? = null
    private var product: ProductF? = null
    var spmPageValue: Int = 0
    var searchWord: String? = null
    var searchWordSource: Int? = null

    //如果心愿单ID不为空 那么直接添加到心愿单 目前只有心愿单详情在使用
    //如果心愿单ID不为空 那么直接添加到心愿单 目前只有心愿单详情在使用
    //如果心愿单ID不为空 那么直接添加到心愿单 目前只有心愿单详情在使用
    var wishListId: String? = null

    //给当前的cardView打一个类型标记 否则引导功能会被抢占
    var guideType: String? = null

    var refreshLayout: SmartRefreshLayout? = null
    var recyclerView: RecyclerView? = null
    var asHomePage: Boolean? = null

    var scene: ProductCardScene? = null

    var position = 0

    var dataPosition = 0

    private val binding: WidgetProductCardBinding = WidgetProductCardBinding.inflate(inflater, this)

    /**
     * 使用merge标签优化的，viewbinding需要bind操作
     */
    private val layoutCardStoreBinding = LayoutCardStoreBinding.bind(binding.layoutStore)
    private val offer1Binding = LayoutCardOfferInfoBinding.bind(binding.layoutOffer1)
    private val offer2Binding = LayoutCardOfferInfoBinding.bind(binding.layoutOffer2)

    //    private val offer1MerchantBinding = LayoutCardMerchantBinding.bind(offer1Binding.root)
//    private val offer2MerchantBinding = LayoutCardMerchantBinding.bind(offer2Binding.root)
    private val storesGoodsCardBinding = LayoutGoodsCardStoresBinding.bind(binding.layoutStoresMore)


    private val findSimilarPop by lazyOnNone {
        GoodsFindSimilarPop(context) {
            doCollectGoods()
        }
    }

    val imgView: ImageView = binding.img

    init {

        context.obtainStyledAttributes(
            attrs,
            com.starblink.library.widget.R.styleable.ProductCardView
        )?.let {
            try {
                scene = it.getEnum(
                    com.starblink.library.widget.R.styleable.ProductCardView_feedsScene,
                    scene
                )
            } catch (ex: Throwable) {
                ex.printStackTrace()
            } finally {
                it.recycle()
            }
        }

        enableCorner(16.dp2px())
//        binding.img.enableCorner(8.dp2px())
        setBackgroundColor(color(R.color.sk_gray0))
        setPadding(0, 0, 0, 12.dp2px())

        binding.img.enableCorner(12.dp2px(), radiusType = "top")
        binding.img.setOnLongClickListener {
            //if (true) return@setOnLongClickListener false
            if (binding.img.drawable == null) return@setOnLongClickListener false

            VibrateUtils.vibrate(100L)
            if (product?.mainImg.isNullOrEmpty() || product?.id.isNullOrEmpty() || product?.type == null) {
                return@setOnLongClickListener false
            }
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    params = SpmTrackHandler.trackProductMap(dataPosition, product!!),
                    traceInfo = product!!.traceInfo ?: "",
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        spmPageValue,
                        SpmElementDef.GOODS_CARD_FIND_SIMILAR,
                    ),
                )
            )

            findSimilarPop.showPopup(
                binding.img,
                product?.mainImg!!,
                product?.id!!,
                product?.type!!,
                add = product?.collected == true
            )
            findSimilarPop.track(
                spmPageValue,
                SpmTrackHandler.trackProductMap(dataPosition, product!!),
                traceInfo = product!!.traceInfo,
            )

            true
        }

        layoutCardStoreBinding.vMore.enableCorner(1000)
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
    }

    /**
     * @param position 视图中的位置
     * @param dataPosition 数据中位置，用于埋点
     */
    @SuppressLint("SetTextI18n")
    fun bindProduct(
        productWrap: IProductFWrap,
        wishListId: String? = null,
        refreshLayout: SmartRefreshLayout? = null,
        recyclerView: RecyclerView? = null,
        spmPageValue: Int = 0,
        position: Int = 0,
        searchWord: String? = null, // 搜索词(仅文搜商品卡片使用)
        searchWordSource: Int? = null, // 搜索词来源(仅文搜商品卡片使用)
        guideType: String? = null,
        asHomePage:Boolean =false,
        onItemClickListener: (() -> Unit)? = null, // Item点击事件回调
    ) {
        this.asHomePage =asHomePage
        this.recyclerView = recyclerView
        this.refreshLayout = refreshLayout
        this.guideType = guideType
        this.wishListId = wishListId
        this.productWrap = productWrap
        this.product = productWrap.productF
        this.spmPageValue = spmPageValue
        this.position = position
        this.searchWord = searchWord
        this.searchWordSource = searchWordSource
        this.dataPosition = productWrap.index
        val product = this.product

        trackData(
            element = SpmElementDef.GoodCollectionCard,
            page = spmPageValue,
            traceInfo = product!!.traceInfo,
            params = SpmTrackHandler.trackProductMap(dataPosition, product).apply {
                if (product.score != null) {
                    put("score", (product.score?.toString() ?: ""))
                }

                if (searchWordSource == SEARCH_WORD_SOURCE_HOT && searchWord != null) {
                    put("trendingWord", searchWord)
                }
                if(searchWord != null){
                    put("searchTerm", searchWord)
                }
                put("searchType" , if (searchWordSource == SEARCH_WORD_SOURCE_HOT) "trendingWord" else if (searchWordSource == SEARCH_WORD_SOURCE_SHADING) "shadingWord" else "normal")
            },
            businessSuffixID = productWrap.trackBizId
        )
        setOnClickListener {
            onItemClickListener?.invoke()
            toProductPage()
        }
        binding.imgCollect.run {
            collectBtnTrack()
            click {
                doCollectGoods()

            }
            binding.imgCollect.setImageResource(R.mipmap.ic_prd_collect)
        }

        // 注册了长按事件消费，需要单独处理点击
        binding.img.click {
            this@ProductCardView.performClick()
        }
        layoutCardStoreBinding.vMerchantBg.trackData(
            element = SpmElementDef.GOODS_CARD_OFFER_CLICK,
            page = spmPageValue,
            traceInfo = product!!.traceInfo,
            params = SpmTrackHandler.trackProductMap(dataPosition, product).apply {
                if (product.score != null) {
                    put("score", (product.score?.toString() ?: ""))
                }
                if (searchWordSource == SEARCH_WORD_SOURCE_HOT && searchWord != null) {
                    put("trendingWord", searchWord)
                }
                if(searchWord != null){
                    put("searchTerm", searchWord)
                }
                put("searchType" , if (searchWordSource == SEARCH_WORD_SOURCE_HOT) "trendingWord" else if (searchWordSource == SEARCH_WORD_SOURCE_SHADING) "shadingWord" else "normal")
            },
            businessSuffixID = productWrap.trackBizId,
            onlyHit = true,
        )
        layoutCardStoreBinding.vMerchantBg.click { toProductPage() }
//        offer1Binding.click { offer1MerchantBinding.root.performClick() }
//        offer2MerchantBinding.vMerchantBg.click { offer2MerchantBinding.root.performClick() }


        binding.img.run {
            updateLayoutParams<LayoutParams> {
                this.dimensionRatio =
                    if (product.mainPicSize.isNullOrEmpty()) "1" else product.mainPicSize?.let {
                        var ratio = 1f
                        try {
                            ratio = it.split("*").let { list ->
                                list[0].toFloat() / list[1].toFloat()
                            }
                        } catch (e: Exception) {
                            SKLogger.e(TAG, e.message ?: "mainPicSize parse erro")
                        }
                        if (ratio.isNaN()) {
                            ratio = 1f
                        }
                        if (ratio < RATIO_LIMIT) {
                            ratio = RATIO_LIMIT
                        }
                        ratio.toString()
                    }
            }
            load(product.mainImg ?: "", format = DecodeFormat.PREFER_RGB_565)
        }

        binding.tvName.text = "${product.title}"

        binding.tvBrandTag.visibleOrGone(product.hotBrand?.name.isNullOrEmpty().not()) {
            text = product.hotBrand?.name?.uppercase()
        }

        //views
//        if ((product.viewNum ?: 0) > 0) {
//            binding.tvViewingNum.visible()
//            binding.tvViewingNum.text = "${product.viewNum} $viewing"
//        } else {
//            binding.tvViewingNum.gone()
//        }

        updateCollect(product.collected)

        //左上角tag card_feeds_child_v2.dart
        handleLeftTopTag()

        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == product.merchantWeb?.id && event.followed != product.merchantWeb?.subOrNot) {
                    product.merchantWeb?.apolloValue("subOrNot", event.followed)
                }
                product.offerList?.forEach {
                    if (event.id == it?.spuOffer?.merchantWeb?.id && event.followed != it?.spuOffer?.merchantWeb?.subOrNot) {
                        it?.spuOffer?.run {
                            this.merchantWeb?.apolloValue("subOrNot", event.followed)
                        }
                    }
                }
                updateSpuInfo()
            }
        }
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) { event ->
            if (event.id != null) {
                if (event.id == this.product?.id) {
                    this.product?.apolloValue("collected", event.collect)
                    updateCollect(this.product?.collected)
                }
                product.offerList?.forEach {
                    if (event.id == it?.spuOffer?.id) {
                        it?.spuOffer?.run {
                            apolloValue("collected", event.collect)
                        }
                    }
                }
            }
        }
        updateSpuInfo()
        //引导弹窗  心愿单没传 不传smartRefresh 不传guideType的 不执行引导流程
        if (recyclerView != null && guideType != null) {
            GuidePopStatusControl.feedsProductPopGuide(
                spmPageValue = spmPageValue,
                dataPosition = dataPosition,
                refreshLayout = refreshLayout,
                recyclerView = recyclerView,
                screenView = binding.imgLay,
                tarView = binding.imgCollect,
                bootView = binding.root as ViewGroup,
                guideType = guideType,
                asHomePage = asHomePage
            )
        }
    }


    private fun toProductPage() {
        product ?: return

        val product = this.product!!
        val toDetail = fun() {
            CommonRoute.startProductDetail(
                productId = product.id ?: "",
                standardSpuIds = product.standardSpuIds ?: "",
                product
            )
        }
        when (scene) {
            ProductCardScene.HOME,
            ProductCardScene.WISH_LIST,
            ProductCardScene.SEARCH_RECOMMEND,
            ProductCardScene.BARCODE_SEARCH_RECOMMEND,
            ProductCardScene.IMAGE_SEARCH_RECOMMEND,
            -> {
                toDetail.invoke()
            }

            ProductCardScene.SEARCH,
            ProductCardScene.IMAGE_SEARCH,
            ProductCardScene.BARCODE_SEARCH,
            ProductCardScene.FIND_SIMILAR,
            ProductCardScene.CATEGORY_GOODS,
            ProductCardScene.CATEGORY_MAIN,
            ProductCardScene.STORE_RECOMMEND,
            -> {
                toGoodsLink(
                    url = product.url,
                    affInfoLink = product.affInfo?.link,
                    id = product.id,
                    productId = product.productId,
                    standardSpuIds = product.standardSpuIds,
                    traceId = product.traceId,
                    type = product.type,
                    collected = product.collected,
                    merchantId = product.merchantWeb?.id,
                    merchantName = product.merchantWeb?.merchantName,
                    merchantLogo = product.merchantWeb?.logo,
                    merchantSubOrNot = product.merchantWeb?.subOrNot,
                )
            }

            else -> {
                toGoodsLink(
                    url = product.url,
                    affInfoLink = product.affInfo?.link,
                    id = product.id,
                    productId = product.productId,
                    standardSpuIds = product.standardSpuIds,
                    traceId = product.traceId,
                    type = product.type,
                    collected = product.collected,
                    merchantId = product.merchantWeb?.id,
                    merchantName = product.merchantWeb?.merchantName,
                    merchantLogo = product.merchantWeb?.logo,
                    merchantSubOrNot = product.merchantWeb?.subOrNot,
                )
            }
        }
    }

    private fun updateCollect(collected: Boolean?) {
        binding.imgCollect.setImageResource(if (collected == true) collectedImg else collectImg)
    }

    private fun collectBtnTrack() {
        product ?: return
        binding.imgCollect.trackData(
            element = SpmElementDef.itemCardCollection,
            page = spmPageValue,
            onlyHit = true,
            traceInfo = product!!.traceInfo,
            params = SpmTrackHandler.trackProductMap(dataPosition, product!!).plus(
                "status" to (if (UserDataCenter.isLogin()) "1" else "0")
            ).plus(
                "result" to (if (product!!.collected == true) "0" else "1")
            )
        )
    }

    /**
     * 左上角标签：折扣标签或商品标签（new_in、trending等）
     */
    private fun handleLeftTopTag() {
        if (product != null && product?.disCountInfo?.discountText?.isNotEmpty() == true) {
            // 有折扣信息，优先显示折扣信息
//            binding.tvLeftTag.gone()
            binding.llDiscount.visible()
            binding.tvDiscount.buildSpannableString {
                addText("Save ") {
                    setColor(Color.parseColor("#FFFFFF"))
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_SEMIBOLD)?.let {
                        setTypeface(it)
                    }
                }

                addText(product!!.disCountInfo?.discountPercent ?: "") {
                    setColor(Color.parseColor("#FFFFFF"))
                    setScale(1.15f)
                    FontUtil.getTypeface(FontUtil.MONTSERRAT_BOLD)?.let {
                        setTypeface(it)
                    }
                }
            }
            product?.disCountInfo?.underlinePrice?.let {
                binding.tvPrice.showStyleHasOff(
                    product!!.price!!,
                    product!!.currency,
                    product!!.currencySymbol
                )
                binding.tvPriceOff.visible()
                binding.tvPriceOff.show(
                    it,
                    product!!.currency,
                    product!!.currencySymbol
                )
            }
        } else {
            // 无折扣信息，显示标签信息
            binding.tvPriceOff.gone()
            binding.llDiscount.gone()
//            if (!product?.cornerLabels.isNullOrEmpty() && product?.cornerLabels!!.isNotEmpty()) {
//                val type = product!!.cornerLabels!![0].type
//                // 商品标签类型（cornerLabels）-1 新品标签 1：new in 2：trending 3：best seller 4：on sale ...
//                if (type == 1 || type == 2) {
//                    binding.tvLeftTag.visible()
//                    binding.tvLeftTag.setBackgroundColor(CommUtils.getColor(R.color.sk_gray800))
//                    binding.tvLeftTagTxt.text = product!!.cornerLabels!![0].title
//                } else {
//                    binding.tvLeftTag.gone()
//                }
//            } else {
//                binding.tvLeftTag.gone()
//            }
        }
    }

    private fun updateSpuInfo() {
        product ?: return

        val productNum = product!!.productNum ?: 0
        if (product?.type == 1 && product?.merchantWeb != null) {
            binding.layoutOffer1.gone()
            binding.layoutOffer2.gone()
            storesGoodsCardBinding.root.gone()
            setPrice()
            val merchant = product?.merchantWeb
            layoutCardStoreBinding.setStore(
                merchant?.logo,
                merchant?.merchantName,
                merchant?.subOrNot,
                false
            )

        } else if (product?.type == 2 && productNum == 1) {
            binding.layoutOffer1.gone()
            binding.layoutOffer2.gone()
            storesGoodsCardBinding.root.gone()

            val merchant = product?.offerList?.first()?.spuOffer?.merchantWeb
            layoutCardStoreBinding.setStore(
                merchant?.logo,
                merchant?.merchantName,
                merchant?.subOrNot,
                false
            )
            setPrice()

        } else if (product?.type == 2 && productNum > 1) {
            if (isSupportSpuStyle()) {
                val offers = product!!.offerList
                layoutCardStoreBinding.root.gone()
                binding.tvPrice.gone()

                if ((offers?.size ?: 0) > 1) {
                    offer1Binding.setOffer(offers!![0]?.spuOffer) {
                        offer1Binding.setMerchant2(it)
                    }
                    offer2Binding.setOffer(offers!![1]?.spuOffer) {
                        offer2Binding.setMerchant2(it)
                    }
                }
                storesGoodsCardBinding.root.visibleOrGone((product!!.logos?.size ?: 0) > 2) {
                    trackData(
                        element = SpmElementDef.GOODS_CARD_OFFER_MORE_CLICK,
                        page = spmPageValue,
                        onlyHit = true,
                        params = baseTrackMap().apply {
                            if (searchWordSource == SEARCH_WORD_SOURCE_HOT && searchWord != null) {
                                put("trendingWord", searchWord!!)
                            }
                            if(searchWord != null){
                                put("searchTerm", searchWord!!)
                            }
                            put("searchType" , if (searchWordSource == SEARCH_WORD_SOURCE_HOT) "trendingWord" else if (searchWordSource == SEARCH_WORD_SOURCE_SHADING) "shadingWord" else "normal")

                        },
                        traceInfo = product!!.traceInfo
                    )
                    click {
                        showParityDialog()
                    }
                    storesGoodsCardBinding.logoMerchant1.loadRect(
                        product!!.logos?.get(0),
                        null
                    )

                    storesGoodsCardBinding.logoMerchant2.loadRect(
                        product!!.logos?.get(1),
                        null
                    )
                    storesGoodsCardBinding.logoMerchant3.loadRect(
                        product!!.logos?.get(2),
                        null
                    )
                    storesGoodsCardBinding.tvStoreNum.text =
                        "In ${product!!.productNum} stores"

                    product!!.productNum?.let { num ->
                        storesGoodsCardBinding.logoMore.run {
                            enableCorner(4.dp)
                            visibleOrGone(num > 3)
                        }
                    }
                    storesGoodsCardBinding.imgMore.enableCorner(1000)
                }
            } else {
                binding.layoutOffer1.gone()
                binding.layoutOffer2.gone()
                storesGoodsCardBinding.root.gone()
                layoutCardStoreBinding.setStore(
                    product?.logos?.first(), "${product!!.productNum}", false,
                    isSpu = true
                )
                setPrice()
            }

        } else {
            binding.layoutOffer1.gone()
            binding.layoutOffer2.gone()
//            binding.layoutStoresMore.gone()
            layoutCardStoreBinding.setStore(null, null)
            setPrice()
        }
    }

    private fun setPrice() {
        binding.tvPriceLay.visibleOrGone(product?.price != null)
        binding.tvPrice.visibleOrGone(product?.price != null) {
            if (product?.disCountInfo?.discountText?.isNotEmpty() == true) {
                showStyleHasOff(
                    product!!.price!!,
                    product!!.currency,
                    product!!.currencySymbol
                )
                product?.disCountInfo?.underlinePrice?.let {
                    binding.tvPriceOff.visible()
//                    binding.tvPriceOff.showStyleHasStrikethrough(
//                        it,
//                        product!!.currency,
//                        product!!.currencySymbol
//                    )
                    binding.tvPriceOff.show(
                        it,
                        product!!.currency,
                        product!!.currencySymbol
                    )
                }
                binding.tvPriceOff.visibleOrGone(product?.disCountInfo?.underlinePrice != null)
            } else {
                binding.tvPriceOff.gone()
                showDefaultColor()
                show(
                    product!!.price!!,
                    product!!.currency,
                    product!!.currencySymbol
                )
            }
            show(
                product!!.price!!,
                product!!.currency,
                product!!.currencySymbol
            )
        }
    }

    //logo方形图标
    private fun LayoutCardStoreBinding.setStore(
        logo: String?,
        name: String?,
        sub: Boolean? = false,
        isSpu: Boolean = false,
    ) {
        if (isSpu && name?.isNotEmpty() == true) {
            root.visible()
            vMore.visible()
            logoRectMerchant.loadRect(logo, null)
            imgMerchantSub.visibleOrGone(sub == true)
            tvStoreName.text = "Sold in $name stores"
        } else if (!isSpu && name?.isNotEmpty() == true) {
            root.visible()
            vMore.gone()
            logoRectMerchant.loadRect(logo, name)
            imgMerchantSub.visibleOrGone(sub == true)
            tvStoreName.text = name
        } else {
            root.gone()
        }
    }

    private fun LayoutCardOfferInfoBinding.setMerchant2(merchant: SpuOffer.MerchantWeb?) {
        // 此处为merge标签优化的，不能直接root.gone，否则整个布局gone
        if (merchant != null) {
            tvStoreName.visible()
            logoMerchant.visible()
            logoMerchant.loadRect(merchant.logo, merchant.merchantName)
            imgMerchantSub.visibleOrInVisible(merchant.subOrNot)
            tvStoreName.text = merchant.merchantName
        } else {
            tvStoreName.gone()
            logoMerchant.gone()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun LayoutCardOfferInfoBinding.setOffer(
        spuOffer: SpuOffer?,
        setupMerchant: ((SpuOffer.MerchantWeb) -> Unit)? = null,
    ) {
        this.root.visibleOrGone(spuOffer != null) {
            trackData(
                element = SpmElementDef.GOODS_CARD_OFFER_CLICK,
                page = spmPageValue,
                onlyHit = true,
                traceInfo = product!!.traceInfo,
                params = mutableMapOf(
                    "id" to (spuOffer!!.id ?: ""),
                    "productId" to (spuOffer!!.productId ?: ""),
                    "standardSpuIds" to (spuOffer!!.standardSpuIds ?: ""),
                    "type" to (spuOffer!!.type.toString()),
                    "merchantName" to (spuOffer?.merchantWeb?.merchantName ?: ""),
                    "index" to (dataPosition.toString()),
                ).apply {
                    if (spuOffer.affInfo != null && !spuOffer.affInfo?.link.isNullOrEmpty()) {
                        put("affInfo", spuOffer.affInfo!!.toJson())
                    }
                    if (searchWordSource == SEARCH_WORD_SOURCE_HOT && searchWord != null) {
                        put("trendingWord", searchWord!!)
                    }
                    if(searchWord != null){
                        put("searchTerm", searchWord!!)
                    }
                    put("searchType" , if (searchWordSource == SEARCH_WORD_SOURCE_HOT) "trendingWord" else if (searchWordSource == SEARCH_WORD_SOURCE_SHADING) "shadingWord" else "normal")

                }
            )
            tvPrice.visibleOrGone(spuOffer?.price != null, goneMode = View.INVISIBLE) {
                this@setOffer.root.post {
                    tvPrice.show(spuOffer.price!!, spuOffer.currency, spuOffer.currencySymbol)
                    tvPrice.setTextSizes(14f, 14f, 12f)
                    val mW = preMeasurePriceWidth(
                        spuOffer!!.price!!,
                        spuOffer!!.currency,
                        spuOffer.currencySymbol
                    )
                    val limitW =
                        this@setOffer.root.measuredWidth * 0.6f - this@setOffer.root.paddingLeft - this@setOffer.root.paddingRight
                    if (mW > limitW) {
                        val ratio = limitW / mW
                        tvPrice.setTextSizes(
                            max(ratio * 14f, 8f),
                            max(4f, ratio * 14f),
                            max(4f, ratio * 12f)
                        )
                        //tvPrice.setTextSizes(ratio * 20f, ratio * 12f, ratio * 12f)
                    }
                }
            }
//            layoutMerchant.visibleOrGone(spuOffer?.merchantWeb != null)
            if (spuOffer?.merchantWeb != null) {
                setupMerchant?.invoke(spuOffer.merchantWeb!!)
            }
            tagKPay.visibleOrGone(spuOffer?.klarnaPayFlag == true)
            tagFreePay.visibleOrGone(spuOffer?.logistics?.shippingTag?.isNotEmpty() == true)
            tagLowest.visibleOrGone(spuOffer?.minimumPriceFlag == true)

            tagOnSale.run {
                visibleOrGone(spuOffer?.minimumPriceFlag != true && !spuOffer.disCountInfo?.discountPercent.isNullOrEmpty())
                text = "Save ${spuOffer.disCountInfo?.discountPercent ?: ""}"
                enableCorner(2.dp)
            }

//            tagFreePay.visibleOrGone(spuOffer?.logistics?.shippingTag?.isNotEmpty() == true || spuOffer?.minimumPriceFlag == true) {
//                if (spuOffer?.logistics?.shippingTag?.isNotEmpty() == true) {
//                    text = if (spuOffer?.minimumPriceFlag == true) {
//                        "${
//                            spuOffer?.logistics?.shippingTag
//                                ?: string(com.starblink.library.widget.R.string.goods_card_free_shopping)
//                        }, ${string(com.starblink.library.widget.R.string.goods_card_low_price)}"
//                    } else {
//                        "${
//                            spuOffer?.logistics?.shippingTag
//                                ?: string(com.starblink.library.widget.R.string.goods_card_free_shopping)
//                        }"
//                    }
//                } else if (spuOffer?.minimumPriceFlag == true) {
//                    text = string(com.starblink.library.widget.R.string.goods_card_low_price)
//                }
//            }

            this.setOnClickListener {
                toGoodsLink(
                    url = spuOffer!!.url,
                    affInfoLink = spuOffer.affInfo?.link,
                    id = spuOffer.id,
                    productId = spuOffer.productId,
                    standardSpuIds = spuOffer.standardSpuIds,
                    traceId = "",
                    type = spuOffer.type,
                    collected = spuOffer.collected,
                    merchantId = spuOffer.merchantWeb?.id,
                    merchantName = spuOffer.merchantWeb?.merchantName,
                    merchantLogo = spuOffer.merchantWeb?.logo,
                    merchantSubOrNot = spuOffer.merchantWeb?.subOrNot,
                )
            }
        }
    }

    private fun toGoodsLink(
        url: String?,
        affInfoLink: String?,
        traceId: String?,
        id: String?,
        productId: String?,
        standardSpuIds: String?,
        type: Int?,
        collected: Boolean?,
        merchantId: String?,
        merchantName: String?,
        merchantLogo: String?,
        merchantSubOrNot: Boolean?,
    ) {
        CommonRoute.startProductLink(
            activity = context,
            webUrl = url,
            id = id ?: "",
            productId = productId ?: "",
            standardSpuIds = standardSpuIds ?: "",
            collect = collected == true,
            type = type ?: 1,
            storeId = merchantId ?: "",
            storeName = merchantName ?: "",
            storeLogo = merchantLogo ?: "",
            storeFollow = merchantSubOrNot ?: false,
            affInfoLink = affInfoLink,
            traceId = traceId ?: ""
        )
//        navigationTo(RoutePage.Product.PAGE_LINK) {
//            extraOf(
//                RoutePage.ARG.ID to productId,
//                RoutePage.Product.TYPE to type,
//                RoutePage.Product.COLLECT to collected,
//                RoutePage.Store.URL to url,
//                RoutePage.Store.STORE_ID to merchantId,
//                RoutePage.Store.SUB_OR_NOT to merchantSubOrNot,
//                RoutePage.Store.STORE_NAME to merchantName,
//                RoutePage.Store.STORE_LOGO to merchantLogo,
//            )
//        }
    }

    private val theScope get() = (context as? AppCompatActivity?)?.lifecycleScope ?: MainScope()

    private fun showParityDialog() {

        if (product?.standardSpuIds.isNullOrEmpty()) {
            toastUI("data error")
            return
        }

        (context as? AppCompatActivity?)?.let { activity ->
            theScope.launch {
                SkGqlClient.skQuery(
                    FetchProductListByStdIdQuery(
                        stdProdcutIdQuery = StdProductIdQuery(
                            stdProductId = product!!.standardSpuIds!!,
                            includeInValidProd = false.optional(),
                        ).optional()
                    ),
                    showDefaultLoading = true,
                )?.data?.fetchProductListByStdId?.run {
                    this.mapNotNull { it?.productOffer }
                }?.let {
                    PriceParityDialog.show(
                        activity.supportFragmentManager,
                        product = product!!,
                        it,
                        spmPageValue = when (scene) {
                            ProductCardScene.SEARCH -> SpmPageDef.PAGE_10193
                            ProductCardScene.IMAGE_SEARCH -> SpmPageDef.PAGE_10194
                            ProductCardScene.FIND_SIMILAR -> SpmPageDef.PAGE_10200
                            ProductCardScene.CATEGORY_MAIN -> SpmPageDef.PAGE_10196
                            ProductCardScene.CATEGORY_GOODS -> SpmPageDef.PAGE_10197
                            else -> 0
                        }
                    )
                }

            }
        }
    }

    private fun doCollectGoods() {
        product?.id ?: return
        val isColl = product!!.collected
        CommonMutateManage.collectProduct(
            ctx = context,
            id = product!!.id!!,
            type = product!!.type,
            scope = theScope,
            collected = (product!!.collected == true),
            refreshState = {
                //测试不要马上刷新状态
//                val collected = product!!.collected?.not() == true
//                updateCollect(collected)
            }, showDialog = (wishListId != null)
        ) { it, collected ->
            if (it) {
                this.product?.apolloValue("collected", collected)
                collectBtnTrack()
                updateCollect(this.product?.collected)
                /*if (product?.collected == true) {
                    (context as? Activity?)?.toastAddWishlist(product?.id!!)
                }*/
                theScope.launch {
                    if (product?.collected == true) {
                        FlowBus.with<ProductF>(FlowConst.WISHLIST_ADD_PRODUCT_VIEW).post(product!!)
                    } else {
                        FlowBus.with<List<ProductF>>(FlowConst.WISHLIST_DELETE_PRODUCT_VIEW)
                            .post(listOf(product!!))
                    }
                }
                if (wishListId == null) {
                    //显示添加心愿单部件
                    val collected = product!!.collected == true
                    binding.btnAddWishlist.visibleOrGone(collected) {
                        trackData(
                            element = SpmElementDef.GOODS_CARD_ADD_BOARD,
                            page = spmPageValue,
                            traceInfo = product!!.traceInfo,
                            params = SpmTrackHandler.trackProductMap(dataPosition, product!!),
                            onlyHit = true
                        )
                        animation =
                            AnimationUtils.loadAnimation(context, android.R.anim.fade_in)
                                .apply {
                                    duration = 500L
                                }
                        animation?.start()
                        this.postDelayed(3000L) {
                            gone()
                        }
                        this.click {
                            WishlistAddBottomDialog.showAddListDialog(
                                context,
                                batchPros = arrayListOf(
                                    BatchProductArrEntry(
                                        id = product!!.id ?: "",
                                        type = product!!.type,
                                        url = product!!.mainImg ?: ""
                                    )
                                ),
                                spmPageValue = spmPageValue
                            )
                        }
                    }
                } else {
//                    if (isColl == false) {
                    //添加到心愿单
                    theScope.launch {
                        val data = SkGqlClient.skMutation(
                            MoveProductList2WishListMutation(
                                items = arrayListOf<CollectItem>().apply {
                                    add(
                                        CollectItem(
                                            id = product!!.id ?: "",
                                            type = product!!.type.optional(),
                                        )
                                    )
                                }.optional(),
                                fromWishListId = Optional.Absent,
                                toWishListId = Optional.present(wishListId!!),
                            ),
                            showDefaultLoading = true,
                        )
                        val success = data?.data?.moveProductList2WishList == true
                        if (success) {
                            FlowBus.with<ProductF>(FlowConst.WISHLIST_ADD_DETAILS)
                                .post(product!!)
                            toast(string(com.starblink.library.widget.R.string.success_added))
                        } else {
                            data?.errors?.getOrNull(0)?.message?.let { msg ->
                                toast(msg)
                            }
                        }
                    }
//                    }
                }
            }
        }

    }


    fun isSupportSpuStyle() =
        scene == ProductCardScene.SEARCH
                || scene == ProductCardScene.IMAGE_SEARCH
                || scene == ProductCardScene.CATEGORY_MAIN
                || scene == ProductCardScene.FIND_SIMILAR
                || scene == ProductCardScene.CATEGORY_GOODS


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
    }

    fun baseTrackMap() = if (product != null) mutableMapOf<String, String>(
        "id" to (product!!.id ?: ""),
        "productId" to (product!!.productId ?: ""),
        "standardSpuIds" to (product!!.standardSpuIds ?: ""),
        "type" to (product!!.type.toString()),
        "index" to (dataPosition.toString()),
    ) else mutableMapOf<String, String>()


}